<template>
  <div class="chart" ref="chart">多轴组合图表
  </div>
</template>
<script>
import * as echarts from 'echarts'
import {data as exampleData} from './example.data'
import {isNumber} from "lodash"

const lineColorList = ['#99d115', '#ffaa00', '#13afba', '#5a1ceb', '#eb2f93']
const barColor = '#9EAEFF'
const xAxisConfigDefault = [
  {
    height: 81,
    rotate: -90,
    offset: 0,
  },
  {
    height: 24,
    rotate: 0,
    offset: 81,
  },
  {
    height: 24,
    rotate: 0,
    offset: 105,
  },
]
const yAxisConfigDefault = [
  {
    name: '',
    type: 'value',
    axisLine: {
      show: true,
    },
  },
  {
    name: '',
    type: 'value',
    axisLine: {
      show: true,
    },
  },
]

function calcOffset(xAxisConfig) {
  xAxisConfig.forEach((config, index) => {
    if (index === 0) {
      config.offset = 0
    } else {
      const tArr = xAxisConfig.slice(0, index)
      const tOffset = tArr.reduce((pre, cur) => {
        return pre + cur.height
      }, 0)
      config.offset = tOffset
    }
  })
}

function getAxisTree(keys) {
  const top = []
  const level = keys[0].split('$').length
  let topLevelKeys = keys.map((key) => key.split('$')[0])
  topLevelKeys = [...new Set(topLevelKeys)].sort()
  topLevelKeys.forEach((key) => {
    const t = {
      key,
    }
    if (level > 1) {
      let children = keys.filter((i) => i.startsWith(key))
      children = children.map((key) => key.split('$').slice(1).join('$'))
      children = getAxisTree(children)
      t.children = children
    }
    top.push(t)
  })
  return top
}

function calcAxisTreeItemSize(tree) {
  tree.forEach((i) => {
    if (i.children) {
      calcAxisTreeItemSize(i.children)
      i.size = i.children.reduce((pre, cur) => pre + cur.size, 0)
    } else {
      i.size = 1
    }
  })
}

function calcAxisArray(tree, deep) {
  const nextLevelFlat = (arr) => {
    const t = arr.map((i) => i.children)
    return t.flat()
  }
  let result = tree
  if (deep === 0) {
    result = result.map((i) => ({key: i.key, size: i.size}))
  } else {
    for (let i = 0; i < deep; i++) {
      result = nextLevelFlat(result)
    }
    result = result.map((i) => ({key: i.key, size: i.size}))
  }
  return result
}

function getTreeData(rawData, tree, prefix = '') {
  const result = []
  tree.forEach((i) => {
    const {key, children} = i
    const rawKey = prefix ? `${prefix}$${key}` : key
    if (!children) {
      const data = rawData[rawKey] || 0
      result.push(data)
    } else {
      const data = getTreeData(rawData, children, rawKey)
      result.push(...data)
    }
  })
  return result
}

function getBaseLevelAxis(axisTree, currentLevel) {
  const axisArray = calcAxisArray(axisTree, currentLevel)
  const data = []
  axisArray.forEach((i) => {
    const {key, size} = i
    data.push(...new Array(size).fill(key))
  })
  const sizes = axisArray.map((t) => Number(t.size))
  const labelIntervalArray = []
  for (let i = 0; i < sizes.length; i++) {
    const t = sizes.slice(0, i)
    const pre = t.reduce((pre, cur) => pre + cur, 0)
    const half = Math.floor(sizes[i] / 2)
    labelIntervalArray.push(pre + half)
  }
  const axis = {
    type: 'category',
    data,
    position: 'bottom',
    axisLine: {
      onZero: false,
    },
    axisTick: {
      show: true,
    },
    axisLabel: {
      show: true,
      showMinLabel: true,
      showMaxLabel: true,
      hideOverlap: false,
      interval: (index) => {
        return labelIntervalArray.includes(index)
      },
    },
  }
  return axis
}

function getNotBaseLevelAxis(axisTree, currentLevel) {
  const axisArray = calcAxisArray(axisTree, currentLevel)
  const data = []
  axisArray.forEach((i) => {
    const {key, size} = i
    data.push(...new Array(size).fill(key))
  })
  const sizes = axisArray.map((t) => Number(t.size))
  const tickIntervalArray = []
  for (let i = 0; i < sizes.length + 1; i++) {
    const t = sizes.slice(0, i)
    const itv = t.reduce((pre, cur) => pre + cur, 0)
    tickIntervalArray.push(itv)
  }
  const labelIntervalArray = []
  for (let i = 0; i < sizes.length; i++) {
    const t = sizes.slice(0, i)
    const pre = t.reduce((pre, cur) => pre + cur, 0)
    const half = Math.floor(sizes[i] / 2)
    labelIntervalArray.push(pre + half)
  }
  const axis = {
    type: 'category',
    data,
    position: 'bottom',
    axisLine: {
      onZero: false,
    },
    axisTick: {
      show: true,
      interval: (index) => {
        return tickIntervalArray.includes(index)
      },
    },
    axisLabel: {
      show: true,
      showMinLabel: true,
      showMaxLabel: true,
      hideOverlap: false,
      interval: (index) => {
        return labelIntervalArray.includes(index)
      },
    },
  }
  return axis
}

function transFiledId(element2, xAxisConfig) {
  const x_axis = []
  let y_data
  //生成x坐标轴
  const x_raw_keys = Object.keys(element2)
  const level = x_raw_keys[0].split('$').length
  const axisTree = getAxisTree(x_raw_keys)
  calcAxisTreeItemSize(axisTree)
  for (let i = 0; i < level; i++) {
    const axis =
        i === level - 1
            ? getBaseLevelAxis(axisTree, i)
            : getNotBaseLevelAxis(axisTree, i)
    x_axis.push(axis)
  }
  x_axis.reverse()
  xAxisConfig.forEach((config, index) => {
    const axis = x_axis[index]
    if (!axis) {
      return
    }
    const {height, rotate, offset} = config
    height !== undefined && (axis.axisTick.length = height)
    rotate !== undefined && (axis.axisLabel.rotate = rotate)
    offset !== undefined && (axis.offset = offset)
  })
  //生成y数据
  y_data = getTreeData(element2, axisTree)
  return {x_axis, y_data, axisTree}
}

function transData(raw, xAxisConfig, rightValuePercent) {
  let x_axis,
      y_data,
      yLineData = []
  for (const key in raw) {
    if (Object.hasOwnProperty.call(raw, key)) {
      const element = raw[key]
      const {fieldId: fieldIdData, rightValues: rightValuesData} =
          element
      // 转化 fieldId
      const {
        x_axis: x,
        y_data: y,
        axisTree,
      } = transFiledId(fieldIdData, xAxisConfig)
      x_axis = x
      y_data = y
      // 提取rightValues
      for (const [k, v] of Object.entries(rightValuesData)) {
        const serie = {
          type: 'line',
          name: k,
          yAxisIndex: 1,
          tooltip: {
            formatter: rightValuePercent
                ? '{a}<br>{b}: <b>{c}%</b>'
                : undefined,
          },
          label: {
            show: true,
            position: 'top',
            formatter: rightValuePercent ? `{c}%` : undefined,
          },
        }
        const {ratio = {}} = v
        serie.data = getTreeData(ratio, axisTree)
        yLineData.push(serie)
      }
    }
  }
  return {x_axis, y_data, yLineData}
}

function genOption(option = {}) {
  const {
    title = '多轴组合图表',
    barTitle = this.stage === 'module'
        ? 'MDL投入的panel数量'
        : '检测站点投入Panel数',
    xAxis,
    yAxis,
    yBarData,
    yLineData,
    xAxisConfig,
    dataZoomEnd,
    grid,
    barLabel,
  } = option
  const dataLength = Math.max(yBarData.length, 60)
  const end = dataZoomEnd || Math.round((60 / dataLength) * 100)
  const finalOption = {
    legend: {
      show: true,
      top: 36,
    },
    tooltip: {
      show: true,
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    title: {
      text: title,
      left: 'center',
      textStyle: {
        color: '#303133',
      },
      triggerEvent: true,
    },
    grid: grid || {
      left: 100,
      right: 100,
      top: 80,
      bottom: xAxisConfig.reduce((pre, cur) => pre + cur.height, 0) + 50,
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end:10,
      },
      {
        type: 'slider',
        start: 0,
        end:10,
      },
    ],
    xAxis,
    yAxis,
    series: [
      {
        type: 'bar',
        name: barTitle,
        data: yBarData,
        barMaxWidth: 30,
        label: {
          show: barLabel,
          position: 'top',
        },
      },
      ...yLineData,
    ]
  }
  return finalOption
}

function isAncestorSame(dataList, currentLevel, index) {
  const parentData = dataList[currentLevel + 1]
  if (parentData) {
    return (
        parentData[index] === parentData[index - 1] &&
        isAncestorSame(dataList, currentLevel + 1, index)
    )
  } else {
    return true
  }
}

function isLabelAncestorSame(dataList, currentLevel, index1, index2) {
  const parentData = dataList[currentLevel + 1]
  if (parentData) {
    return (
        parentData[index1] === parentData[index2] &&
        isLabelAncestorSame(dataList, currentLevel + 1, index1, index2)
    )
  } else {
    return true
  }
}

export default {
  props: {
    test: {
      type: Boolean,
      default: false,
    },
    agile: {
      type: Boolean,
      default: false,
    },
    stage: {
      type: String,
      default: 'module',
    },
    labelCenter: {
      type: Boolean,
      default: true,
    },
    mergeLastChild: {
      type: Boolean,
      default: false,
    },
    defectType: {
      type: String,
      default: 'RATIO',
    },
  },
  data() {
    return {
      chart: null,// 图表实例
      brushResult: [], //框选结果
      observer: null
    }
  },
  activated() {
    // console.log(this.test);
    // console.log(this.agile);
    // console.log(this.stage);
    // console.log(this.labelCenter);
  },
  mounted() {
    this.init()
    this.initObserver()
    window.addEventListener('resize', this.onChartResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onChartResize)
    if (this.observer) {
      this.observer.disconnect()
    }
  },
  methods: {
    onChartClear() {
      this.chart && this.chart.clear()
    },
    onChartResize() {
      this.chart && this.$nextTick(() => this.chart?.resize())
    },
    initObserver() {
      this.observer = new IntersectionObserver(([entry]) => {
        const isVisible = entry.isIntersecting
        isVisible && this.onChartResize()
      })
      this.observer.observe(this.$refs.chart)
    },
    init() {
      this.chart = echarts.init(this.$refs.chart)
      this.chart.off('dblclick');
      this.chart.on('dblclick', ({componentType, value}) => {
        let text;
        if (componentType === 'title' || componentType === 'xAxis') {
          text = componentType === 'title' ? this.chart.getOption().title[0].text : value
          this.$copyText(text).then(() => {
            this.$message.success('复制成功')
          }, () => {
            this.$message.success('复制失败')
          });
        }
      })
    },
    setOption(option = {}) {
      const {
        rawData = exampleData,
        title,
        barTitle,
        rightValuePercent = false,
        xAxisConfig = xAxisConfigDefault,
        yAxisConfig = yAxisConfigDefault,
        dataZoomEnd,
        grid,
        barLabel = true,
      } = option
      // 计算offset
      calcOffset(xAxisConfig)
      const {
        x_axis: xAxis,
        y_data: yBarData,
        yLineData,
      } = transData(rawData, xAxisConfig, rightValuePercent)
      const finalOption = genOption({
        title,
        barTitle,
        xAxis,
        yAxis: yAxisConfig,
        yBarData,
        yLineData,
        xAxisConfig,
        dataZoomEnd,
        grid,
        barLabel,
      })
      this.chart && this.chart.clear()
      this.chart && this.chart.setOption(finalOption)
    },

    setTreatedOption(option, xAxisConfig, yAxisConfig, config = {}) {

      option.title.triggerEvent = true
      const {lineIndex} = config
      calcOffset(xAxisConfig)
      let yAxis = yAxisConfig || [
        {
          name: 'Input',
          type: 'value',
          nameGap: 30,
          axisLine: {
            show: true,
          },
        },
        {
          name: this.defectType === "RATIO" ? "不良Ratio" : "不良数",
          type: 'value',
          nameGap: 30,
          axisLine: {
            show: true,
          },
          axisLabel: {
            formatter: (value) => {
              return this.defectType === "RATIO" ? value + "%" : value
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
            },
          },
        },
      ]
      option.xAxis.reverse()
      const xAxisDataList = option.xAxis.map((i) => i.data)
      const zoomEnd = parseInt((48 / xAxisDataList[0].length) * 100)
      option.dataZoom = [
        {
          type: 'inside',
          // start: 0,
          // end: zoomEnd,
          startValue: 0,
          endValue: 17,
          maxValueSpan: 600,
        },
        {
          type: 'slider',
          // start: 0,
          // end: zoomEnd,
          startValue: 0,
          endValue: 17,
          maxValueSpan: 600,
          show: true
        },
      ]
      option.yAxis = yAxis
      option.grid = {
        left: 100,
        right: 100,
        top: 80,
        bottom:
            xAxisConfig.reduce((pre, cur) => pre + cur.height, 0) + 50,
      }
      option.legend = {
        show: false,
        top: 36,
        formatter: (name) => {
          return name.length > 15 ? name.substring(0, 15) + '...' : name;
        },
        type: 'scroll',
        tooltip: {
          show: true,
          position: 'bottom',
          extraCssText: 'white-space: pre-wrap;',
          formatter: (params) => {
            const tip = params.name.match(/.{1,100}/g).join('\n');
            return tip
          }
        }
      }
      // 此处加上敏捷分析定制的tooltip
      option.tooltip = this.agile
          ? {
            show: true,
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999',
              },
            },
            formatter: (params) => {
              // 如果出现散点图，对散点图的显示单独处理
              const scatterItem = params.find(item => item.seriesType === 'scatter');
              if (scatterItem) {
                let str = ''
                const spanStart =
                        '<span style="display: inline-block; width: 80px;">',
                    spanEnd = '</span>'
                if (scatterItem.data.info.operateDesc) {
                  str += `${spanStart}${scatterItem.data.info.operateDesc}${spanEnd} <br />`
                }
                if (scatterItem.data.info.operateStartTime) {
                  str += `开始时间${spanStart}${scatterItem.data.info.operateStartTime.split(' ')[0]}${spanEnd} <br />`
                }
                if (scatterItem.data.info.operateEndTime) {
                  str += `结束时间${spanStart}${scatterItem.data.info.operateEndTime.split(' ')[0]}${spanEnd} <br />`
                }
                return str
              } else {
                let str = ''
                const spanStart =
                        '<span style="display: inline-block; width: 80px;">',
                    spanEnd = '</span>'
                const bar = params.find((i) => i.seriesType === 'bar')
                if (bar) {
                  //bar.data.value[1]为了兼容某个柱状图改了颜色之后的取值
                  str += `${bar.marker}${spanStart}Input:${spanEnd} ${bar.data[1] || bar.data.value[1]}<br />`
                }
                params.forEach((i) => {
                  if (i.seriesType === 'line') {
                    let _val = i.data[2]
                    str += `${
                        i.marker
                    }${spanStart}不良数:${spanEnd} ${
                        _val === undefined || _val === 'undefined'
                            ? ''
                            : _val
                    }<br />`
                    if (this.defectType === "RATIO") {
                      str += `${i.marker}${spanStart}不良Ratio:${spanEnd} ${i.data[1]}%<br />`
                    }
                    if (isNumber(i.data[3])) {
                      str += `${i.marker}${spanStart}RT比例: ${spanEnd} ${i.data[3]}%<br />`
                    }
                  }
                })
                return str
              }
            },
          }
          : {
            show: true,
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999',
              },
            },
          }
      option.xAxis = option.xAxis.map((i, index) => {
        const config = xAxisConfig[index]
        return {
          ...i,
          type: 'category',
          data: i.data,
          position: 'bottom',
          axisLine: {
            onZero: false,
          },
          triggerEvent: true,
          axisTick: {
            show: true,
            length: (config && config['height']) || 24,
            interval: (j) => {
              if (index === 0 && !this.mergeLastChild) {
                return true
              } else {
                //父级是否相同，父级及祖先相同，本级也相同才可省略tick
                const selfLevelSame =
                    i.data[j] === i.data[j - 1]
                const ancestorSame = isAncestorSame(
                    xAxisDataList,
                    index,
                    j
                )
                return !(ancestorSame && selfLevelSame)
              }
            },
          },
          axisLabel: {
            show: true,
            showMinLabel: true,
            showMaxLabel: true,
            alignMinLabel: !config?.rotate ? 'left' : undefined,
            // alignMaxLabel: !config['rotate'] ? 'right' : undefined,
            align: !config?.rotate ? 'center' : undefined,
            hideOverlap: false,
            rotate: (config && config['rotate']) || 0,
            interval: (j) => {
              if (index === 0 && !this.mergeLastChild) {
                return true
              } else {
                if (this.labelCenter) {
                  let sameBefore = 0,
                      sameBeforeFlag = true
                  while (sameBeforeFlag) {
                    const selfLevelSame =
                        i.data[j] === i.data[j - sameBefore]
                    const ancestorSame =
                        isLabelAncestorSame(
                            xAxisDataList,
                            index,
                            j,
                            j - sameBefore
                        )
                    if (selfLevelSame && ancestorSame) {
                      sameBefore++
                    } else {
                      sameBeforeFlag = false
                    }
                  }
                  let sameAfter = 0,
                      sameAfterFlag = true
                  while (sameAfterFlag) {
                    const selfLevelSame =
                        i.data[j] === i.data[j + sameAfter]
                    const ancestorSame =
                        isLabelAncestorSame(
                            xAxisDataList,
                            index,
                            j,
                            j + sameAfter
                        )
                    if (selfLevelSame && ancestorSame) {
                      sameAfter++
                    } else {
                      sameAfterFlag = false
                    }
                  }
                  return [-1, 0].includes(
                      sameBefore - sameAfter
                  )
                } else {
                  const selfLevelSame =
                      i.data[j] === i.data[j - 1]
                  const ancestorSame = isAncestorSame(
                      xAxisDataList,
                      index,
                      j
                  )
                  return !(ancestorSame && selfLevelSame)
                }
              }
            },
          },
          offset: (config && config['offset']) || 0,
        }
      })
      const seriesBar = option.series.find((i) => i.type === 'bar')
      seriesBar &&
      Object.assign(seriesBar, {
        yAxisIndex: 0,
        barMaxWidth: 30,
        large: true,
        largeThreshold: 100,
        progressive: 100,
        progressiveThreshold: 200,
        itemStyle: {
          color: barColor,
        },
        label: {
          // show: true,
          // position: 'top',
          // formatter: (n) => {
          //     let label = ''
          //     if (option.series && option.series[0] && option.series[0].data && option.series[0].data[n.dataIndex]) {
          //         label = option.series[0].data[n.dataIndex][2]
          //     }
          //     return label
          // },
        },
      })
      const seriesLine = option.series.find((i) => i.type === 'line')
      seriesLine &&
      Object.assign(seriesLine, {
        label: {
          show: true,
          position: 'top',
          // rotate: -45,
          formatter: this.defectType === "RATIO" ? '{@1}%' : '{@2}',
        },
      })
      option.series
          .filter((s) => s.type === 'line')
          .forEach((i, index) => {
            i.yAxisIndex = 1
            i.symbol = 'circle'
            i.symbolSize = 8
            if (lineColorList[index]) {
              i.itemStyle = {
                color: lineColorList[index],
                borderColor: '#fff',
                borderWidth: 2,
                borderType: 'solid',
              }
            }
            i.encode = {
              x: 0,      // 使用第 0 列作为 x 轴
              y: this.defectType === "RATIO" ? 1 : 2,
            }
          })
      const _serLine = option.series.filter((i) => i.type === 'line')
      const _serNoLine = option.series.filter((i) => i.type !== 'line')
      option.series = [..._serLine, ..._serNoLine]
      const names = option.series.map((i) => i.name)
      seriesBar && names.unshift(seriesBar.name)
      option.legend.data = [...new Set(names)].map((i) => {
        return {name: i}
      })
      option.brush = { //框选功能
        toolbox: [],
        // xAxisIndex: [0],
        brushLink: 'all',
        throttleType: 'debounce', // 防抖，避免频繁触发
        throttleDelay: 300,// 防抖延迟时间
        outOfBrush: {
          colorAlpha: 1
        }
      }
      this.chart && this.chart.clear()
      this.chart && this.chart.off('click')
      this.chart && this.chart.setOption(option)
      this.chart && this.chart.on('click', (e) => {
        const {dataIndex} = e
        const xAxis = xAxisDataList.map((i) => i[dataIndex])
        this.$emit('chart-click', {...e, xAxis})
      })
    },
    handleMappingOn() { //开始绘制
      this.enableWheelZoom(false)//取消dataZoom缩放事件
      this.chart.dispatchAction({
        type: 'takeGlobalCursor', //设置空则为关闭选区功能
        key: 'brush',
        brushOption: {
          brushType: 'lineX',
          brushMode: 'multiple' //多选
        }
      });
      //选矿选择结束事件
      this.chart.on('brushEnd', (event) => {
        //选区完毕添加对应文字
        var areas = [];
        for (var i = 0; i < event.areas.length; i++) {
          areas.push({
            type: 'text', // 类型为文本
            // x: event.areas[i].range[0][0],
            // y: event.areas[i].range[1][0] - 15,
            x: event.areas[i].range[0] + 5,
            y: 0 + 5,
            z: 10,
            style: {
              text: 'mapping' + (i + 1), // 文本内容
              fill: '#333', // 文字颜色
              fontSize: 14 // 文字大小
            }
          });
        }
        this.chart.setOption({
          graphic: areas
        });
        this.getBrushResult(event.areas)
      });
      //选框选择事件
      // this.chart.on('brushSelected', (event) => {
      // 	console.log(event)
      // });
    },
    handleMappingOff() { //结束绘制
      this.brushResult = []
      this.enableWheelZoom(true)//取消dataZoom缩放事件
      //清除所有文字
      if (this.chart && this.chart.getOption() && this.chart.getOption().graphic) {
        var graphic = this.chart.getOption().graphic[0].elements;
        var _arr = [];
        for (var i = 0; i < graphic.length; i++) {
          _arr.push({
            id: graphic[i].id,
            $action: 'remove'
          });
        }
        this.chart.setOption({
          graphic: _arr
        });
      }
      //初始化echart option
      var option = this.chart.getOption();
      this.chart && this.chart.clear()
      this.chart && this.chart.setOption(option)
    },
    //启用禁用鼠标滚轮缩放
    enableWheelZoom(enable) {
      let option = this.chart.getOption()
      for (let i = 0; i < option.dataZoom.length; i++) {
        console.log(option.dataZoom[i].type);
        if (option.dataZoom[i].type == 'inside') {
          option.dataZoom[i].disabled = !enable ? true : false
        }
        if (option.dataZoom[i].type == 'slider') {
          option.dataZoom[i].show = !enable ? false : true
          // option.dataZoom[i].disabled =  !enable ? false : true//不起作用  不知道为啥
          // option.dataZoom[i].zoomLock =  !enable ? false : true//不起作用  不知道为啥
        }
      }
      // this.chart && this.chart.clear()
      this.chart && this.chart.setOption(option)
    },
    getBrushResult(areas) { //根据区域坐标范围获取dataIndex
      this.brushResult = []
      for (let i = 0; i < areas.length; i++) {
        var start = areas[i].range[0];
        var end = areas[i].range[1];
        const startValue = this.chart.convertFromPixel({xAxisIndex: 0}, start);
        const endValue = this.chart.convertFromPixel({xAxisIndex: 0}, end);
        this.brushResult.push({
          start: startValue < 0 ? 0 : startValue,
          end: endValue,
        })
      }
    },
    getMappingResult(
        proIndex = -1,
        dateIndex = -1,
        hourIndex = -1,
        unitIndex = -1,
        detectionUnitIndex = -1,
    ) {
      let result = []
      let option = this.chart.getOption()
      let all_xAxisProductData = option.xAxis[proIndex]?.data || [] // glsProductID
      let all_xAxisDateData = option.xAxis[dateIndex]?.data || [] //天别-日期 glsTimeKey
      let all_xAxisDateUnit = option.xAxis[unitIndex]?.data || [] //unitId
      let all_xAxisHourData = option.xAxis[hourIndex]?.data || [] //小时别-小时 glsHourKey
      let all_xAxisDateDetectionUnit = option.xAxis[detectionUnitIndex]?.data || [] // detectionUnitId

      let all_lineData = option.series.find((i) => i.type === 'line').data
      let all_barData = option.series.find((i) => i.type === 'bar').data
      console.log(this.brushResult);
      for (let i = 0; i < this.brushResult.length; i++) {
        result.push({
          xAxisProduct: [],
          xAxisUnit: [],
          xAxisdetectionUnit: [],
          xAxisDate: [],
          xAxisHour: [],
          lineData: [],
          barData: [],
        })
        for (let j = this.brushResult[i].start; j <= this.brushResult[i].end; j++) {
          all_xAxisProductData.length > 0 && result[i].xAxisProduct.push(all_xAxisProductData[j])
          all_xAxisDateData.length > 0 && result[i].xAxisDate.push(all_xAxisDateData[j])
          all_xAxisDateUnit.length > 0 && result[i].xAxisUnit.push(all_xAxisDateUnit[j])
          all_xAxisHourData.length > 0 && result[i].xAxisHour.push(all_xAxisDateData[j] + all_xAxisHourData[j])
          all_xAxisDateDetectionUnit.length > 0 && result[i].xAxisdetectionUnit.push(all_xAxisDateDetectionUnit[j])
          result[i].lineData.push(all_lineData[j])
          result[i].barData.push(all_barData[j])
        }

      }
      this.$emit('setMapping', result)
    },

  },
}
</script>

<style scoped lang="stylus">
.chart
  width 100%
  height 600px
  // border 1px solid var(--table-border-color)
  background-size 60%
  background-repeat no-repeat
  background-position center center
</style>
